import 'package:aero_frisbee/app/state/af_app_state_ext.dart';
import 'package:aero_frisbee/app/state/app_cache_state.dart';
import 'package:aero_frisbee/app_route.dart';
import 'package:aero_frisbee/core/extension/string_ext.dart';
import 'package:aero_frisbee/core/tools/af_log_manager.dart';
import 'package:aero_frisbee/gen/assets.gen.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:permission_handler/permission_handler.dart';

import 'view_model/af_login_view_model.dart';
import 'views/af_login_confirm_pop_view.dart';

final isAgreeLoginProvider = StateProvider.autoDispose<bool>((ref) {
  return false;
});

class AFLoginPage extends ConsumerStatefulWidget {
  const AFLoginPage({super.key});
  @override
  ConsumerState<ConsumerStatefulWidget> createState() => _AFLoginPageState();
}

class _AFLoginPageState extends ConsumerState<AFLoginPage> {
  @override
  Widget build(BuildContext context) {
    ref.listen(afLoginAppleServiceProvider, (previousData, newData) {
      newData.showError();
      newData.showLoadding();
      final retItem =
          newData.maybeWhen(ready: ((data) => data), orElse: () => null);
      if (retItem != null) {
        AFLogPvManger.stat(page: AFLogPages.loginSuccess);
        "login success".toast(
          onDismiss: () {
            ref.read(appCacheServiceProvider.notifier).logined(retItem);
          },
        );
      }
    });
    final isAgreen = ref.watch(isAgreeLoginProvider);
    return Scaffold(
      body: Stack(
        children: [
          Positioned.fill(
            child: Assets.images.launchBg.image(fit: BoxFit.fill),
          ),
          LayoutBuilder(
            builder: (BuildContext context, BoxConstraints constraints) {
              return SizedBox(
                height: constraints.maxHeight,
                width: constraints.maxWidth,
                child: Column(
                  children: [
                    Expanded(
                      child: Container(),
                    ),
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        if (isAgreen) {
                          ref
                              .read(afLoginAppleServiceProvider.notifier)
                              .appleLogin();
                          AFLogPvManger.stat(page: AFLogPages.appleLogin);
                        } else {
                          showLoginConfirmPopView(
                            context,
                            onTapClick: () {
                              ref.read(isAgreeLoginProvider.notifier).state =
                                  true;
                            },
                          );
                        }
                      },
                      child: Container(
                        margin: const EdgeInsets.symmetric(horizontal: 60),
                        decoration: BoxDecoration(
                          color: const Color(0xffDDFB6C),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Stack(children: [
                          Row(
                            children: [
                              Padding(
                                padding: const EdgeInsets.only(
                                    left: 35, top: 15, bottom: 15),
                                child: Assets.images.login.loginAppleBtn
                                    .image(width: 24),
                              )
                            ],
                          ),
                          const Positioned.fill(
                            child: Align(
                              alignment: Alignment.center,
                              child: Text(
                                'Sign in with Apple',
                                style: TextStyle(
                                  color: Color(0xff202020),
                                  fontWeight: FontWeight.w500,
                                  fontSize: 16,
                                ),
                                textAlign: TextAlign.left,
                                overflow: TextOverflow.ellipsis,
                                maxLines: 1,
                              ),
                            ),
                          )
                        ]),
                      ),
                    ),
                    const SizedBox(
                      height: 30,
                    ),
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        if (isAgreen) {
                          ref
                              .read(afLoginAppleServiceProvider.notifier)
                              .fastLogin();
                          AFLogPvManger.stat(page: AFLogPages.quickLogin);
                        } else {
                          showLoginConfirmPopView(
                            context,
                            onTapClick: () {
                              ref.read(isAgreeLoginProvider.notifier).state =
                                  true;
                            },
                          );
                        }
                      },
                      child: Container(
                        margin: const EdgeInsets.symmetric(horizontal: 60),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Stack(
                          children: [
                            Row(
                              children: [
                                Padding(
                                  padding: const EdgeInsets.only(
                                      left: 35, top: 15, bottom: 15),
                                  child: Assets.images.login.loginFastBtn
                                      .image(width: 24),
                                )
                              ],
                            ),
                            const Positioned.fill(
                              child: Align(
                                alignment: Alignment.center,
                                child: Text(
                                  'Fast Login',
                                  style: TextStyle(
                                    color: Color(0xff202020),
                                    fontWeight: FontWeight.w500,
                                    fontSize: 16,
                                  ),
                                  textAlign: TextAlign.left,
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 1,
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(
                      height: 40,
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 60),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () {
                              ref.read(isAgreeLoginProvider.notifier).state =
                                  !ref
                                      .read(isAgreeLoginProvider.notifier)
                                      .state;
                            },
                            child: Padding(
                              padding: const EdgeInsets.only(
                                  left: 10, right: 8, top: 5, bottom: 15),
                              child: isAgreen
                                  ? Assets.images.login.loginAgreenSelected
                                      .image(width: 16)
                                  : Assets.images.login.loginAgreenUnselected
                                      .image(width: 16),
                            ),
                          ),
                          Expanded(
                            child: RichText(
                              textAlign: TextAlign.left,
                              text: TextSpan(
                                text: " By using our App you agree with our",
                                style: const TextStyle(
                                  color: Color(0xffffffff),
                                  fontWeight: FontWeight.normal,
                                  fontSize: 12,
                                ),
                                children: <TextSpan>[
                                  TextSpan(
                                    text: " Term of Use ",
                                    style: const TextStyle(
                                      color: Color(0xffFFE400),
                                      fontWeight: FontWeight.normal,
                                      fontSize: 12,
                                    ),
                                    recognizer: TapGestureRecognizer()
                                      ..onTap = () {
                                        AFLogPvManger.stat(
                                            page: AFLogPages.terms);
                                        context.pushNamed(RouteUri.webViewPage,
                                            queryParams: {
                                              "title": "Terms and Conditions",
                                              "url":
                                                  'https://h5.heeru.xyz/termConditions.html'
                                            });
                                      },
                                  ),
                                  const TextSpan(
                                    text: "and",
                                    style: TextStyle(
                                      color: Color(0xffffffff),
                                      fontWeight: FontWeight.normal,
                                      fontSize: 12,
                                    ),
                                  ),
                                  TextSpan(
                                    text: " Privacy Policy.",
                                    style: const TextStyle(
                                      color: Color(0xffFFE400),
                                      fontWeight: FontWeight.normal,
                                      fontSize: 12,
                                    ),
                                    recognizer: TapGestureRecognizer()
                                      ..onTap = () {
                                        AFLogPvManger.stat(
                                            page: AFLogPages.privacy);
                                        context.pushNamed(RouteUri.webViewPage,
                                            queryParams: {
                                              "title": "Privacy Policy",
                                              "url":
                                                  'https://h5.heeru.xyz/privacyPolicy.html'
                                            });
                                      },
                                  ),
                                ],
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                    SizedBox(
                      height: MediaQuery.of(context).padding.bottom + 20,
                    ),
                  ],
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      if (!await Permission.appTrackingTransparency.isGranted) {
        Permission.appTrackingTransparency.request();
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didUpdateWidget(AFLoginPage oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}
